import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { NzTableModule } from 'ng-zorro-antd/table';
import { Data, items } from '../data100';
import { NzDropDownModule } from 'ng-zorro-antd/dropdown';
import { NzIconModule } from 'ng-zorro-antd/icon';

@Component({
  selector: 'app-table-selection-custom',
  standalone: true,
  imports: [NzTableModule, CommonModule, NzDropDownModule, NzIconModule],
  templateUrl: './table-selection-custom.component.html',
  styleUrl: './table-selection-custom.component.less',
})
export class TableSelectionCustomComponent {
  readonly listOfData = items;
  private _listOfCurrentPageData: readonly Data[] = [];
  private _selectedData = new Set<Data>();

  onPageChange(rows: readonly Data[]) {
    this._listOfCurrentPageData = rows;
  }

  private _selectAll = false;
  private _indeterminate = false;

  get selectAll() {
    return this._selectAll;
  }

  get indeterminate() {
    return this._indeterminate;
  }

  onSelectAll() {
    const data = this._listOfCurrentPageData.filter((data) => !data.disabled);
    data.forEach((item) => {
      this._selectedData.add(item);
    });
    this.refreshStatus();
  }

  onSelectPage(checked: boolean) {
    const data = this._listOfCurrentPageData.filter((data) => !data.disabled);
    if (checked) {
      data.forEach((item) => {
        this._selectedData.add(item);
      });
    } else {
      data.forEach((item) => {
        this._selectedData.delete(item);
      });
    }
    this.refreshStatus();
  }

  onSelectItem(data: Data, checked: boolean) {
    if (checked) {
      this._selectedData.add(data);
    } else {
      this._selectedData.delete(data);
    }
    this.refreshStatus();
  }

  refreshStatus() {
    const data = this._listOfCurrentPageData.filter((data) => !data.disabled);
    this._selectAll =
      data.every((item) => this._selectedData.has(item)) && data.length > 0;
    this._indeterminate =
      this._selectedData.size > 0 && this._selectedData.size < data.length;
  }

  isChecked(data: Data) {
    return this._selectedData.has(data);
  }
}
